package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.burgeon.backend.SHOP.service.SystemService;
import com.burgeon.backend.SHOPBACKEND.entity.Goods;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendGoodsMapper;
import com.burgeon.backend.SHOPBACKEND.service.BackendLiveService;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.Util.menu.MyX509TrustManager;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;

@Service
public class BackendLiveServiceImpl implements BackendLiveService {
    @Autowired
    private BackendGoodsMapper backendGoodsMapper;
    @Autowired
    private SystemService systemService;


    public void delLiveGoodstest(String id, String account) throws ErrorDataException {


        String accesToken = systemService.GetAccesToken(account);
        String url = "https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token=" + accesToken;
        HashMap data = new HashMap();
        data.put("goodsId", id);
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);

    }

    @Override
    public void delLiveGoods(String id, String account) throws ErrorDataException {

        String gid = backendGoodsMapper.findGoodsLiveId(id);

        String accesToken = systemService.GetAccesToken(account);
        String url = "https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token=" + accesToken;
        HashMap data = new HashMap();
        data.put("goodsId", gid);
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);
        JSONObject res = JSONObject.parseObject(str);
        String errcode = res.getString("errcode");
        if (!"0".equals(errcode)) {
            throw new ErrorDataException(res.getString("errmsg"));
        }
        backendGoodsMapper.upGoodsLiveId(id, null);

    }

    @Override
    public void andLiveGoods(String id, String account) throws ErrorDataException {
        //查询商品
        Goods goods = backendGoodsMapper.getGoodsById(id);
        //上传素材
        String accesToken = systemService.GetAccesToken(account);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accesToken + "&type=image";
        String filePath = goods.getImg().replace("http://lfwdcdn.cloudsmicro.com","/root/code");
        //String filePath = "C:/Users/86177/Desktop/c11/1-0.jpg";
        String bsuffixName = filePath.substring(filePath.lastIndexOf("."));
        String targetPath = "/root/code/img/liveCache/" + account + "/" + id + bsuffixName;

        File mdest = new File(targetPath);
        if (!mdest.getParentFile().exists()) {
            mdest.getParentFile().mkdirs();
        }
        try {
            Thumbnails.of(filePath)
                    .size(300, 300)
                    .keepAspectRatio(false)
                    .toFile(targetPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = doPostForm(url, targetPath);
        String media_id = jsonObject.getString("media_id");
        System.err.println(media_id);
        //添加商品
        url = "https://api.weixin.qq.com/wxaapi/broadcast/goods/add?access_token=" + accesToken;

        HashMap data = new HashMap();
        HashMap goodsInfo = new HashMap();
        goodsInfo.put("coverImgUrl", media_id);
        if (goods.getName().trim().length() > 14) {
            goods.setName(goods.getName().trim().substring(0, 14));
        }
        goodsInfo.put("name", goods.getName().trim());
        goodsInfo.put("priceType", 1);
        goodsInfo.put("price", goods.getPrice());
        goodsInfo.put("url", "pages/productStart/productStart?id=" + id + "&empName=");


        data.put("goodsInfo", goodsInfo);
        System.err.println(data);
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);
        JSONObject res = JSONObject.parseObject(str);
        String errcode = res.getString("errcode");
        if (!"0".equals(errcode)) {
            throw new ErrorDataException(res.getString("errmsg"));
        }

        backendGoodsMapper.upGoodsLiveId(id, res.getString("goodsId"));

    }


    /**
     * POST请求 - Form格式数据
     *
     * @param url      请求地址
     * @param filePath 文件本地路径
     * @return
     */
    public JSONObject doPostForm(String url, String filePath) {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new UploadException("文件不存在");
        }
        System.err.println(url);
        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL urlObj = new URL(url);
            // 连接
            HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
            con.setSSLSocketFactory(ssf);

            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);

            // 设置请求头信息
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");

            // 设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            String sb = "--" +
                    BOUNDARY +
                    "\r\n" +
                    "Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n" +
                    "Content-Type:application/octet-stream\r\n\r\n";

            byte[] head = sb.getBytes("utf-8");

            // 获得输出流
            OutputStream out = new DataOutputStream(con.getOutputStream());
            // 输出表头
            out.write(head);

            // 文件正文部分
            // 把文件已流文件的方式 推入到url中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();

            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

            out.write(foot);

            out.flush();
            out.close();

            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = null;
            String result = null;
            try {
                // 定义BufferedReader输入流来读取URL的响应
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                result = buffer.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

            return JSONObject.parseObject(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }


}
